package com.gdut.simple.view.activity.common;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;

import com.gdut.simple.R;
import com.gdut.simple.basic.BasicApplication;
import com.gdut.simple.common.LogUtils;
import com.gdut.simple.common.RequestCallback;
import com.gdut.simple.common.ToastUtils;
import com.gdut.simple.data.entity.PhotoFolder;
import com.gdut.simple.model.IPhotoPickModel;
import com.gdut.simple.model.impl.PhotoPickModelImpl;
import com.gdut.simple.view.adapter.PhotoFolderAdapter;
import com.gdut.simple.view.adapter.PhotoPickAdapter;
import com.gdut.simple.view.basic.AbsBasicActivity;
import com.gdut.simple.view.widget.PhotoSpinnerWindow;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PhotoPickActivity extends AbsBasicActivity {

    @BindView(R.id.id_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.id_image_grid_view)
    RecyclerView mImageGridView;
    @BindView(R.id.id_bottom_bar)
    RelativeLayout mBottomBar;
    @BindView(R.id.id_photo_spinner)
    Button mSpinnerButton;
    @BindView(R.id.id_photo_preview)
    Button mPreviewButton;

    private PhotoPickAdapter mPhotoPickAdapter;
    private List<String> mPhotoList;

    private PhotoFolderAdapter mPhotoFolderAdapter;
    private List<PhotoFolder> mPhotoFolderList;
    private PhotoSpinnerWindow mPhotoSpinnerWindow;

    private static List<String> mSelectedPhotos = new ArrayList<>();
    private static int mResultCode = RESULT_OK;
    private static int mSelectedCount = 9;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_photo_pick);
        ButterKnife.bind(this);
        initToolbar();
        initGirdView();
        initPhotoWindow();
        getPermission();
    }

    private void initToolbar() {
        mToolbar.setTitle("选择图片");
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }

    private void initGirdView() {
        mSelectedPhotos.clear();  // 清空内存数据
        mPreviewButton.setEnabled(false);  // 初始不可预览
        mImageGridView.setLayoutManager(new GridLayoutManager(this, 3));
        mImageGridView.setItemAnimator(new DefaultItemAnimator());
        mPhotoList = new ArrayList<>();
        mPhotoPickAdapter = new PhotoPickAdapter(this, "", mPhotoList);
        mImageGridView.setAdapter(mPhotoPickAdapter);
        mImageGridView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Picasso.with(PhotoPickActivity.this).resumeTag(mPhotoPickAdapter.getTag());
                } else {
                    Picasso.with(PhotoPickActivity.this).pauseTag(mPhotoPickAdapter.getTag());
                }
            }
        });
        mPhotoPickAdapter.setOnItemSelectedListener(new PhotoPickAdapter.OnItemSelectedListener() {
            @Override
            public void onChecked(CompoundButton compoundButton, String image) {
                if (check(compoundButton)) {
                    mSelectedPhotos.add(image);
                }
                checkSelectedPhotoCount();
            }

            @Override
            public void onRemoved(String image) {
                mSelectedPhotos.remove(image);
                checkSelectedPhotoCount();
            }
        });
    }

    private void checkSelectedPhotoCount() {
        if (mSelectedPhotos == null) return;
        if (mSelectedPhotos.size() == 0) {
            mPreviewButton.setText("预览");
            mPreviewButton.setEnabled(false);
        } else {
            mPreviewButton.setEnabled(true);
            mPreviewButton.setText(String.format(Locale.getDefault(), "预览(%d)", mSelectedPhotos.size()));
        }
    }

    private boolean check(CompoundButton compoundButton) {
        if (mSelectedPhotos.size() + 1 > mSelectedCount) {
            compoundButton.setChecked(false);
            showMessage(String.format(Locale.getDefault(), "您最多能选择%d张图片", mSelectedCount));
            return false;
        }
        return true;
    }

    private void initPhotoWindow() {
        mPhotoFolderList = new ArrayList<>();
        mPhotoFolderAdapter = new PhotoFolderAdapter(this, mPhotoFolderList);
        mPhotoSpinnerWindow = new PhotoSpinnerWindow(this, mPhotoFolderList, new PhotoSpinnerWindow.OnItemSelectedListener() {
            @Override
            public void onSelected(View view, String dir, String name, List<String> images) {
                mSpinnerButton.setText(name);
                mPhotoPickAdapter.setCurrentFolder(dir, images);
                mPhotoSpinnerWindow.dismiss();
            }
        });
    }

    private static final int EXTERNAL_STORAGE_PERMISSION_CODE = 1000;

    private void getPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(PhotoPickActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    EXTERNAL_STORAGE_PERMISSION_CODE);
        } else {
            loadImage();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == EXTERNAL_STORAGE_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadImage();
            } else {
                showMessage("未授权");
            }
        }
    }

    private void loadImage() {
        IPhotoPickModel model = new PhotoPickModelImpl();
        model.getPhotoes(BasicApplication.getApplication(), new RequestCallback<List<PhotoFolder>>() {
            @Override
            public void onSuccess(List<PhotoFolder> photoFolders) {
                LogUtils.i("getPhotoList");
                mPhotoFolderList.clear();
                mPhotoFolderList.addAll(photoFolders);
                mPhotoFolderAdapter.notifyDataSetChanged();
                //
                String dir = photoFolders.get(0).getDir();
                String name = photoFolders.get(0).getName();
                mSpinnerButton.setText(name);
                File file = new File(dir);
                if (file.list() != null) {
                    List<String> images = new ArrayList<>();
                    for (String path : file.list()) {
                        images.add(dir + File.separator + path);
                    }
                    mPhotoPickAdapter.setCurrentFolder(dir, images);
                }
            }

            @Override
            public void onFailure(String message) {
                ToastUtils.showShort(BasicApplication.getApplication(), message);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_done, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_done) {
            Intent intent = new Intent();
            intent.putStringArrayListExtra("data", (ArrayList<String>) mSelectedPhotos);
            setResult(mResultCode, intent);
            finish();
        }
        return true;
    }

    public static void startActivityForResult(Activity context, int requestCode, int resultCode) {
        mResultCode = resultCode;
        Intent intent = new Intent(context, PhotoPickActivity.class);
        context.startActivityForResult(intent, requestCode);
    }

    public static void startActivityForResult(Activity context, int requestCode, int resultCode, int selectedCount) {
        mResultCode = resultCode;
        mSelectedCount = selectedCount;
        Intent intent = new Intent(context, PhotoPickActivity.class);
        context.startActivityForResult(intent, requestCode);
    }

    @OnClick(R.id.id_photo_spinner)
    void photoSpinner() {
        mPhotoSpinnerWindow.showAtLocation(mBottomBar, Gravity.BOTTOM, 0, 0);
    }

    @OnClick(R.id.id_photo_preview)
    void photoPreview() {
        PhotoPreviewActivity.startActivity(PhotoPickActivity.this, (ArrayList<String>) mSelectedPhotos, 0);
    }
}
